package ar.edu.unlu.sistemas.p2p.business.strategy.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import ar.edu.unlu.sistemas.p2p.business.file.FileController;
import ar.edu.unlu.sistemas.p2p.business.index.IndexController;
import ar.edu.unlu.sistemas.p2p.business.peer.PeerController;
import ar.edu.unlu.sistemas.p2p.business.strategy.ProcessQueryStrategy;
import ar.edu.unlu.sistemas.p2p.business.util.Constants;
import ar.edu.unlu.sistemas.p2p.business.vo.QueryProcessVO;
import ar.edu.unlu.sistemas.p2p.business.vo.QueryResultVO;

public class ProcessQueryPerformedStrategyImpl extends ProcessQueryStrategy {
	
	public Collection<QueryResultVO> execute(String query) {
		int queryId = FileController.geInstance().addQuery(query);
		Iterator<QueryProcessVO> allDocs = IndexController.getInstance().processQuery(queryId).iterator();
		Collection<QueryResultVO> queryResults = new ArrayList<QueryResultVO>();
		int sqSumId = IndexController.getInstance().findWordByName(Constants.SQUARE_SUM_WORD).getId();
		float sqSumQuery = IndexController.getInstance().findTFByWordDocument(sqSumId, queryId).getValue();
		QueryProcessVO qpVO;
		Double ac;
		while (allDocs.hasNext()) {
			qpVO = allDocs.next();
			ac = qpVO.getValue()/(Math.sqrt(IndexController.getInstance().findTFByWordDocument(sqSumId, qpVO.getDoc().getId()).getValue())*Math.sqrt(sqSumQuery));
			queryResults.add(new QueryResultVO(PeerController.getInstance().getLocalPeer().getAddress(),qpVO.getDoc().getName(),ac.floatValue()));
		}
		IndexController.getInstance().removeDoc(queryId);
		return this.filterResults(queryResults);
	}

}
